home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / UNTEXTINDEX.PY < prev    next >
Encoding:
Python Source  |  2000-11-13  |  20.5 KB  |  650 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64.  
  65. """Text Index
  66.  
  67. The UnTextIndex falls under the 'I didnt have a better name for it'
  68. excuse.  It is an 'Un' Text index because it stores a little bit of
  69. undo information so that objects can be unindexed when the old value
  70. is no longer known.
  71.  
  72.  
  73. """
  74. __version__='$Revision: 1.23.2.6 $'[11:-2]
  75.  
  76. from Globals import Persistent
  77. import BTree, IIBTree, IOBTree, OIBTree
  78. from Acquisition import Implicit
  79. BTree=BTree.BTree
  80. IOBTree=IOBTree.BTree
  81. IIBucket=IIBTree.Bucket
  82. OIBTree=OIBTree.BTree
  83. from intSet import intSet
  84. import operator
  85. from Splitter import Splitter
  86. from string import strip
  87. import string, regex, regsub, ts_regex
  88. from zLOG import LOG, ERROR
  89.  
  90.  
  91. from Lexicon import Lexicon, stop_word_dict
  92. from ResultList import ResultList
  93.  
  94.  
  95. AndNot    = 'andnot'
  96. And       = 'and'
  97. Or        = 'or'
  98. Near = '...'
  99. QueryError='TextIndex.QueryError'
  100.  
  101.             
  102.  
  103. class UnTextIndex(Persistent, Implicit):
  104.  
  105.     meta_type = 'Text Index'
  106.  
  107.     def __init__(self, id=None, ignore_ex=None,
  108.                  call_methods=None, lexicon=None):
  109.         """Create an index
  110.  
  111.         The arguments are:
  112.  
  113.           'id' -- the name of the item attribute to index.  This is
  114.           either an attribute name or a record key.
  115.  
  116.           'ignore_ex' -- Tells the indexer to ignore exceptions that
  117.           are rasied when indexing an object.
  118.  
  119.           'call_methods' -- Tells the indexer to call methods instead
  120.           of getattr or getitem to get an attribute.
  121.  
  122.           'lexicon' is the lexicon object to specify, if None, the
  123.           index will use a private lexicon.
  124.  
  125.         There is a ZCatalog UML model that sheds some light on what is
  126.         going on here.  '_index' is a BTree which maps word ids to
  127.         mapping from document id to score.  Something like:
  128.  
  129.           {'bob' : {1 : 5, 2 : 3, 42 : 9}}
  130.           {'uncle' : {1 : 1}}
  131.  
  132.  
  133.         The '_unindex' attribute is a mapping from document id to word 
  134.         ids.  This mapping allows the catalog to unindex an object:
  135.  
  136.           {42 : ('bob', 'is', 'your', 'uncle')
  137.  
  138.         This isn't exactly how things are represented in memory, many
  139.         optimizations happen along the way.
  140.  
  141.         """
  142.         if not id==ignore_ex==call_methods==None:
  143.             self.id=id
  144.             self.ignore_ex=ignore_ex
  145.             self.call_methods=call_methods
  146.             self._index=IOBTree()
  147.             self._unindex=IOBTree()
  148.  
  149.         else:
  150.             pass
  151.  
  152.         if lexicon is None:
  153.  
  154.             ## if no lexicon is provided, create a dumb one
  155.             self._lexicon=Lexicon()
  156.         else:
  157.             self._lexicon = lexicon
  158.  
  159.  
  160.     def __setstate(self, state):
  161.         Persistent.__setstate__(self, state)
  162.         if hasattr(self, '_syn'):
  163.             del self._syn
  164.  
  165.     def getLexicon(self, vocab_id):
  166.         
  167.         """ bit of a hack, indexes have been made acquirers so that
  168.         they can acquire a vocabulary object from the object system in 
  169.         Zope.  I don't think indexes were ever intended to participate 
  170.         in this way, but I don't see too much of a problem with it.
  171.         """
  172.         if type(vocab_id) is not type(""):
  173.             vocab = vocab_id
  174.         else:
  175.             vocab = getattr(self, vocab_id)
  176.         return vocab.lexicon
  177.         
  178.  
  179.     def __len__(self):
  180.         return len(self._unindex)
  181.  
  182. ##    def __setstate__(self, state):
  183. ##        Persistent.__setstate__(self, state)
  184. ##        if not hasattr(self, '_lexicon'):
  185. ##            self._lexicon = Lexicon()
  186.         
  187.  
  188.     def clear(self):
  189.         self._index = IOBTree()
  190.         self._unindex = IOBTree()
  191.  
  192.  
  193.     def index_object(self, i, obj, threshold=None, tupleType=type(()),
  194.                      dictType=type({}), strType=type(""), callable=callable):
  195.         
  196.         """ Index an object:
  197.  
  198.           'i' is the integer id of the document
  199.  
  200.           'obj' is the objects to be indexed
  201.  
  202.           'threshold' is the number of words to process between
  203.           commiting subtransactions.  If 'None' subtransactions are
  204.           not used.
  205.  
  206.           the next four arguments are default optimizations.
  207.           """
  208.         # Before we do anything, unindex the object we've been handed, as
  209.         # we can't depend on the user to do the right thing.
  210.         self.unindex_object(i)
  211.         
  212.         id = self.id
  213.         try:
  214.             ## sniff the object for our 'id', the 'document source' of 
  215.             ## the index is this attribute.  If it smells callable,
  216.             ## call it.
  217.             k = getattr(obj, id)
  218.             if callable(k):
  219.                 k = str(k())
  220.             else:
  221.                 k = str(k)
  222.         except:
  223.             return 0
  224.         
  225.         d = OIBTree()
  226.         old = d.has_key
  227.         last = None
  228.  
  229.         ## The Splitter should now be european compliant at least.
  230.         ## Someone should test this.
  231.  
  232. ##        import pdb
  233. ##        pdb.set_trace()
  234.         
  235.         src = self.getLexicon(self._lexicon).Splitter(k)
  236.         ## This returns a tuple of stemmed words.  Stopwords have been 
  237.         ## stripped.
  238.         
  239.         for s in src:
  240.             if s[0] == '\"': last=self.subindex(s[1:-1], d, old, last)
  241.             else:
  242.                 if old(s):
  243.                     if s != last: d[s] = d[s]+1
  244.                 else: d[s] = 1
  245.  
  246.         index = self._index
  247.         unindex = self._unindex
  248.         lexicon = self.getLexicon(self._lexicon)
  249.         get = index.get
  250.         unindex[i] = []
  251.         times = 0
  252.  
  253.         for word, score in d.items():
  254.             if threshold is not None:
  255.                 if times > threshold:
  256.                     # commit a subtransaction hack
  257.                     get_transaction().commit(1)
  258.                     # kick the cache
  259.                     self._p_jar.cacheFullSweep(1)
  260.                     times = 0
  261.                     
  262.             word_id = lexicon.set(word)
  263.             
  264.             r = get(word_id)
  265.             if r is not None:
  266.                 r = index[word_id]
  267.                 if type(r) is tupleType:
  268.                     r = {r[0]:r[1]}
  269.                     r[i] = score
  270.  
  271.                     index[word_id] = r
  272.                     unindex[i].append(word_id)
  273.                     
  274.                 elif type(r) is dictType:
  275.                     if len(r) > 4:
  276.                         b = IIBucket()
  277.                         for k, v in r.items(): b[k] = v
  278.                         r = b
  279.                     r[i] = score
  280.  
  281.                     index[word_id] = r
  282.                     unindex[i].append(word_id)
  283.                     
  284.                 else:
  285.                     r[i] = score
  286.                     unindex[i].append(word_id)
  287.             else:
  288.                 index[word_id] = i, score
  289.                 unindex[i].append(word_id)
  290.             times = times + 1
  291.  
  292.         unindex[i] = tuple(unindex[i])
  293.         l = len(unindex[i])
  294.         
  295.         self._index = index
  296.         self._unindex = unindex
  297.  
  298.         ## return the number of words you indexed
  299.         return times
  300.  
  301.     def unindex_object(self, i, tt=type(()) ): 
  302.         """ carefully unindex document with integer id 'i' from the text
  303.         index and do not fail if it does not exist """
  304.         index = self._index
  305.         unindex = self._unindex
  306.         val = unindex.get(i, None)
  307.         if val is not None:
  308.             for n in val:
  309.                 v = index.get(n, None)
  310.                 if type(v) is tt:
  311.                     del index[n]
  312.                 elif v is not None:
  313.                     try:
  314.                         del index[n][i]
  315.                     except (KeyError, IndexError, TypeError):
  316.                         LOG('UnTextIndex', ERROR,
  317.                             'unindex_object tried to unindex nonexistent'
  318.                             ' document %s' % str(i))
  319.             del unindex[i]
  320.             self._index = index
  321.             self._unindex = unindex
  322.  
  323.     def __getitem__(self, word):
  324.         """Return an InvertedIndex-style result "list"
  325.         """
  326.         src = tuple(self.getLexicon(self._lexicon).Splitter(word))
  327.         if not src: return ResultList({}, (word,), self)
  328.         if len(src) == 1:
  329.             src=src[0]
  330.             if src[:1]=='"' and src[-1:]=='"': return self[src]
  331.             r = self._index.get(self.getLexicon(self._lexicon).get(src)[0],
  332.                                 None)
  333.             if r is None: r = {}
  334.             return ResultList(r, (src,), self)
  335.             
  336.         r = None
  337.         for word in src:
  338.             rr = self[word]
  339.             if r is None: r = rr
  340.             else: r = r.near(rr)
  341.  
  342.         return r
  343.  
  344.  
  345.     def _apply_index(self, request, cid='', ListType=[]): 
  346.         """ Apply the index to query parameters given in the argument,
  347.         request
  348.  
  349.         The argument should be a mapping object.
  350.  
  351.         If the request does not contain the needed parameters, then
  352.         None is returned.
  353.  
  354.         Otherwise two objects are returned.  The first object is a
  355.         ResultSet containing the record numbers of the matching
  356.         records.  The second object is a tuple containing the names of
  357.         all data fields used.  
  358.         """
  359.  
  360.         id = self.id
  361.  
  362.         if request.has_key(id):
  363.             keys = request[id]
  364.         else:
  365.             return None
  366.  
  367.         if type(keys) is type(''):
  368.             if not keys or not strip(keys):
  369.                 return None
  370.             keys = [keys]
  371.         r = None
  372.         
  373.         for key in keys:
  374.             key = strip(key)
  375.             if not key:
  376.                 continue
  377.             
  378.             rr = IIBucket()
  379.             try:
  380.                  for i, score in self.query(key).items():
  381.                     if score:
  382.                         rr[i] = score
  383.             except KeyError:
  384.                 pass
  385.             if r is None:
  386.                 r = rr
  387.             else:
  388.                 # Note that we *and*/*narrow* multiple search terms.
  389.                 r = r.intersection(rr) 
  390.  
  391.         if r is not None:
  392.             return r, (id,)
  393.         return IIBucket(), (id,)
  394.  
  395.  
  396.     def positions(self, docid, words, obj):
  397.         """Return the positions in the document for the given document
  398.         id of the word, word."""
  399.         id = self.id
  400.  
  401.         if self._schema is None:
  402.             f = getattr
  403.         else:
  404.             f = operator.__getitem__
  405.             id = self._schema[id]
  406.  
  407.  
  408.         if self.call_methods:
  409.             doc = str(f(obj, id)())
  410.         else:
  411.             doc = str(f(obj, id))
  412.  
  413.         r = []
  414.         for word in words:
  415.             r = r+self.getLexicon(self._lexicon).Splitter(doc).indexes(word)
  416.         return r
  417.  
  418.  
  419.     def _subindex(self, isrc, d, old, last):
  420.  
  421.         src = self.getLexicon(self._lexicon).Splitter(isrc)  
  422.  
  423.         for s in src:
  424.             if s[0] == '\"': last=self.subindex(s[1:-1],d,old,last)
  425.             else:
  426.                 if old(s):
  427.                     if s != last: d[s] = d[s]+1
  428.                 else: d[s] = 1
  429.  
  430.         return last
  431.  
  432.  
  433.     def query(self, s, default_operator = Or, ws = (string.whitespace,)):
  434.         """
  435.  
  436.         This is called by TextIndexes.  A 'query term' which is a string
  437.         's' is passed in, along with an index object.  s is parsed, then
  438.         the wildcards are parsed, then something is parsed again, then the 
  439.         whole thing is 'evaluated'
  440.  
  441.         """
  442.  
  443.         # First replace any occurences of " and not " with " andnot "
  444.         s = ts_regex.gsub(
  445.             '[%s]+[aA][nN][dD][%s]*[nN][oO][tT][%s]+' % (ws * 3),
  446.             ' andnot ', s)
  447.  
  448.  
  449.         # do some parsing
  450.         q = parse(s)
  451.  
  452.         ## here, we give lexicons a chance to transform the query.
  453.         ## For example, substitute wildcards, or translate words into
  454.         ## various languages.
  455.         q = self.getLexicon(self._lexicon).query_hook(q)
  456.  
  457.         # do some more parsing
  458.         q = parse2(q, default_operator)
  459.  
  460.         ## evalute the final 'expression'
  461.         return self.evaluate(q)
  462.  
  463.  
  464.     def get_operands(self, q, i, ListType=type([]), StringType=type('')):
  465.         '''Evaluate and return the left and right operands for an operator'''
  466.         try:
  467.             left  = q[i - 1]
  468.             right = q[i + 1]
  469.         except IndexError: raise QueryError, "Malformed query"
  470.  
  471.         t=type(left)
  472.         if t is ListType: left = evaluate(left, self)
  473.         elif t is StringType: left=self[left]
  474.  
  475.         t=type(right)
  476.         if t is ListType: right = evaluate(right, self)
  477.         elif t is StringType: right=self[right]
  478.  
  479.         return (left, right)
  480.  
  481.  
  482.     def evaluate(self, q, ListType=type([])):
  483.         '''Evaluate a parsed query'''
  484.     ##    import pdb
  485.     ##    pdb.set_trace()
  486.  
  487.         if (len(q) == 1):
  488.             if (type(q[0]) is ListType):
  489.                 return evaluate(q[0], self)
  490.  
  491.             return self[q[0]]
  492.  
  493.         i = 0
  494.         while (i < len(q)):
  495.             if q[i] is AndNot:
  496.                 left, right = self.get_operands(q, i)
  497.                 val = left.and_not(right)
  498.                 q[(i - 1) : (i + 2)] = [ val ]
  499.             else: i = i + 1
  500.  
  501.         i = 0
  502.         while (i < len(q)):
  503.             if q[i] is And:
  504.                 left, right = self.get_operands(q, i)
  505.                 val = left & right
  506.                 q[(i - 1) : (i + 2)] = [ val ]
  507.             else: i = i + 1
  508.  
  509.         i = 0
  510.         while (i < len(q)):
  511.             if q[i] is Or:
  512.                 left, right = self.get_operands(q, i)
  513.                 val = left | right
  514.                 q[(i - 1) : (i + 2)] = [ val ]
  515.             else: i = i + 1
  516.  
  517.         i = 0
  518.         while (i < len(q)):
  519.             if q[i] is Near:
  520.                 left, right = self.get_operands(q, i)
  521.                 val = left.near(right)
  522.                 q[(i - 1) : (i + 2)] = [ val ]
  523.             else: i = i + 1
  524.  
  525.         if (len(q) != 1): raise QueryError, "Malformed query"
  526.  
  527.         return q[0]
  528.  
  529.  
  530. def parse(s):
  531.     '''Parse parentheses and quotes'''
  532.     l = []
  533.     tmp = string.lower(s)
  534.  
  535.     while (1):
  536.         p = parens(tmp)
  537.  
  538.         if (p is None):
  539.             # No parentheses found.  Look for quotes then exit.
  540.             l = l + quotes(tmp)
  541.             break
  542.         else:
  543.             # Look for quotes in the section of the string before
  544.             # the parentheses, then parse the string inside the parens
  545.             l = l + quotes(tmp[:(p[0] - 1)])
  546.             l.append(parse(tmp[p[0] : p[1]]))
  547.  
  548.             # continue looking through the rest of the string
  549.             tmp = tmp[(p[1] + 1):]
  550.  
  551.     return l
  552.  
  553. def parse2(q, default_operator,
  554.            operator_dict = {AndNot: AndNot, And: And, Or: Or, Near: Near},
  555.            ListType=type([]),
  556.            ):
  557.     '''Find operators and operands'''
  558.     i = 0
  559.     isop=operator_dict.has_key
  560.     while (i < len(q)):
  561.         if (type(q[i]) is ListType): q[i] = parse2(q[i], default_operator)
  562.  
  563.         # every other item, starting with the first, should be an operand
  564.         if ((i % 2) != 0):
  565.             # This word should be an operator; if it is not, splice in
  566.             # the default operator.
  567.             
  568.             if type(q[i]) is not ListType and isop(q[i]):
  569.                 q[i] = operator_dict[q[i]]
  570.             else: q[i : i] = [ default_operator ]
  571.  
  572.         i = i + 1
  573.  
  574.     return q
  575.  
  576.  
  577. def parens(s, parens_re = regex.compile('(\|)').search):
  578.  
  579.     index=open_index=paren_count = 0
  580.  
  581.     while 1:
  582.         index = parens_re(s, index)
  583.         if index < 0 : break
  584.     
  585.         if s[index] == '(':
  586.             paren_count = paren_count + 1
  587.             if open_index == 0 : open_index = index + 1
  588.         else:
  589.             paren_count = paren_count - 1
  590.  
  591.         if paren_count == 0:
  592.             return open_index, index
  593.         else:
  594.             index = index + 1
  595.  
  596.     if paren_count == 0: # No parentheses Found
  597.         return None
  598.     else:
  599.         raise QueryError, "Mismatched parentheses"      
  600.  
  601.  
  602.  
  603. def quotes(s, ws = (string.whitespace,)):
  604.      # split up quoted regions
  605.      splitted = ts_regex.split(s, '[%s]*\"[%s]*' % (ws * 2))
  606.      split=string.split
  607.  
  608.      if (len(splitted) > 1):
  609.          if ((len(splitted) % 2) == 0): raise QueryError, "Mismatched quotes"
  610.     
  611.          for i in range(1,len(splitted),2):
  612.              # split the quoted region into words
  613.              splitted[i] = filter(None, split(splitted[i]))
  614.  
  615.              # put the Proxmity operator in between quoted words
  616.              for j in range(1, len(splitted[i])):
  617.                  splitted[i][j : j] = [ Near ]
  618.  
  619.          for i in range(len(splitted)-1,-1,-2):
  620.              # split the non-quoted region into words
  621.              splitted[i:i+1] = filter(None, split(splitted[i]))
  622.  
  623.          splitted = filter(None, splitted)
  624.      else:
  625.          # No quotes, so just split the string into words
  626.          splitted = filter(None, split(s))
  627.  
  628.      return splitted
  629.